package com.gxuwz.stats.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.stats.entity.User;
import com.gxuwz.stats.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/researchAward")
public class ResearchAwardController {

    @Autowired
    private UserService userService;

    /**
     * 获取用户列表
     * @param params 请求参数
     * @param currentPage 当前页码
     * @param pageSize    每页大小
     * @return
     */
    @GetMapping("/userList")
    public ResponseEntity<Map<String, Object>> userList(
            @RequestParam Map<String, String> params,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize) {
        try {
            // 创建 MyBatis Plus 的 Page 对象进行分页查询
            IPage<User> page = new Page<>(currentPage, pageSize);
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();

            // 模糊查询条件
            if (params.containsKey("userKeyword") && !params.get("userKeyword").isEmpty()) {
                String keyword = "%" + params.get("userKeyword") + "%";
                queryWrapper.and(wrapper -> wrapper
                        .like("username", keyword)
                        .or().like("role", keyword)
                        .or().like("degree", keyword)
                        .or().like("position", keyword)
                        .or().like("post", keyword)
                        .or().like("department", keyword));
            }

            // 调用 service 层的分页查询方法
            IPage<User> resultPage = userService.page(page, queryWrapper);

            // 构造返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", resultPage.getRecords()); // 当前页数据
            response.put("total", resultPage.getTotal()); // 总记录数
            response.put("currentPage", resultPage.getCurrent()); // 当前页码
            response.put("pageSize", resultPage.getSize()); // 每页大小
            response.put("totalPages", resultPage.getPages()); // 总页数

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    @PostMapping("/importData")
    public ResponseEntity<Map<String, Object>> importData(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) {
        try {
            List<User> users = userService.importExcel(file.getInputStream(), updateSupport);
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "导入成功");
            response.put("data", users);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 400);
            errorResponse.put("message", "导入失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse);
        }
    }

    /**
     * 新增用户
     */
    @PostMapping("/addUser")
    public ResponseEntity<Void> addUser(@RequestBody User user) {

        System.out.println("user==="+user);
        // 检查密码是否为空或未提供，默认设置为 "123456"
        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            user.setPassword(new BCryptPasswordEncoder().encode("123456"));
        }
        userService.save(user);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/deleteUser")
    public ResponseEntity<Void> deleteUser(@RequestBody List<Long> userIds) {
        System.out.println("删除："+userIds);
        userService.removeByIds(userIds);
        return ResponseEntity.noContent().build();
    }

    /**
     * 修改用户
     */
    @PutMapping("/editUser")
    public ResponseEntity<Void> editUser(@RequestBody User user) {
        System.out.println("user::"+user);
        userService.updateById(user);
        return ResponseEntity.ok().build();
    }

    /**
     * 获取到当前登录的用户
     * @param authentication
     * @return
     */
    @GetMapping("/current")
    public ResponseEntity<Map<String, Object>> getCurrentUser(Authentication authentication) {
        System.out.println("11111="+authentication);
        if (authentication == null || !authentication.isAuthenticated()) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }

        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        System.out.println("当前登录："+userDetails);

        Map<String, Object> response = new HashMap<>();
        response.put("username", userDetails.getUsername());
        response.put("password", userDetails.getPassword());
//        response.put("role", userDetails.getRole());
//        response.put("degree", userDetails.getDegree());
//        response.put("position", userDetails.getPosition());
//        response.put("post", userDetails.getPost());
//        response.put("department", userDetails.getDepartment());
//        response.put("quotaStandard", userDetails.getQuotaStandard());

        return ResponseEntity.ok(response);
    }
}
